﻿using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Lost{
	public class DataSaver {
		public static Texture2D SaveRenderTexture(RenderTexture renderTex, string savePath){
			Texture2D t2d = DataSaver.ToTextrue2D (renderTex);
			DataSaver.SaveTexture2D (t2d, savePath);
			return t2d;
		}

		public static void SaveData<T>(T data, string filePath){
			byte[] bytes = ToBytes<T> (data);
			FileStream fs = new FileStream(filePath, FileMode.Create);
			fs.Write(bytes, 0, bytes.Length);
			fs.Close ();
		}

		public static T LoadData<T>(string filePath){
			FileStream fs = new FileStream(filePath, FileMode.Open);
			BinaryFormatter bf = new BinaryFormatter ();
			T data = (T)bf.Deserialize (fs);
			fs.Close ();
			return data;
		}

		public static byte[] ToBytes<T>(T type){
			BinaryFormatter bf = new BinaryFormatter ();
			MemoryStream ms = new MemoryStream ();
			bf.Serialize (ms, type);
			return ms.GetBuffer ();
		}

		public static Texture2D ToTextrue2D(RenderTexture renderTex){
			int width = renderTex.width;
			int height = renderTex.height;
			Texture2D t2d = new Texture2D (width, height, TextureFormat.ARGB32, false);
			RenderTexture.active = renderTex;
			t2d.ReadPixels (new Rect (0, 0, width, height), 0, 0);
			t2d.Apply ();
			RenderTexture.active = null;
			return t2d;
		}

		public static IEnumerator LoadAssetBundle(string url){
			url = "file://" + Application.dataPath + url;
			WWW www = WWW.LoadFromCacheOrDownload (url, 5);
			yield return www;
			AssetBundle assetBundle = www.assetBundle;
			return assetBundle;

			//string url = Application.dataPath + "/StreamingAssets/photoes";
			//AssetBundle AB = AssetBundle.LoadFromFile (url);
		}

		public static void CopyFile(string regionFile, string newFile){
			FileStream fs;
			fs = new FileStream (regionFile, FileMode.Open);
			int len = (int)fs.Length;
			byte[] bytes = new byte[len];
			fs.Read (bytes, 0, len);
			fs.Close ();
			fs = new FileStream(newFile, FileMode.CreateNew);
			fs.Write(bytes, 0, len);
			fs.Close ();
		}

		public static void SaveTexture2D(Texture2D t2d, string path){
			FileStream fs = new FileStream (path, FileMode.Create);
			byte[] bytes = t2d.EncodeToPNG ();
			fs.Write (bytes, 0, bytes.Length);
			fs.Close ();
		}

		public static Texture2D LoadTexture2D(string path){
			FileStream fs = new FileStream (path, FileMode.Open);
			int len = (int)fs.Length;
			byte[] bytes = new byte[len];
			fs.Read (bytes, 0, len);
			fs.Close ();
			Texture2D t2d = new Texture2D (128, 128);
			t2d.LoadImage (bytes);
			t2d.Apply ();
			return t2d;
		}
	}
}